import { defineStore } from 'pinia'
import { ref } from 'vue'

export const usePlacementStore = defineStore('placement', () => {
  const isPlacing = ref(false)
  const item = ref(null)
  const image = ref(null)
  const position = ref({ x: 0, y: 0 })
  const size = ref({ width: 80, height: 80 })

  const startPlacement = (libraryItem) => {
    item.value = libraryItem
    isPlacing.value = true
    position.value = { x: -9999, y: -9999 }

    // 预加载图片
    const img = new Image()
    img.onload = () => {
      image.value = img
      // 基于原图设置一个合适的初始尺寸（等比缩放到最长边 120）
      const maxSide = 120
      const scale = Math.min(1, maxSide / Math.max(img.naturalWidth || img.width, img.naturalHeight || img.height))
      size.value = {
        width: Math.max(40, (img.naturalWidth || img.width) * scale),
        height: Math.max(40, (img.naturalHeight || img.height) * scale)
      }
    }
    img.src = libraryItem.thumbnail
  }

  const updatePosition = (x, y) => {
    position.value = { x, y }
  }

  const confirmPlacement = () => {
    isPlacing.value = false
    item.value = null
    image.value = null
  }

  const cancelPlacement = () => {
    isPlacing.value = false
    item.value = null
    image.value = null
  }

  return {
    isPlacing,
    item,
    image,
    position,
    size,
    startPlacement,
    updatePosition,
    confirmPlacement,
    cancelPlacement
  }
})


